package com.exp.bookhouse.util;

import com.github.tobato.fastdfs.domain.fdfs.ThumbImageConfig;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class UploadService {

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private ThumbImageConfig thumbImageConfig;      //缩略图使用

//    @Value("${images.path}")
//    private String upUrl;

//    @Value("${baseUploadUrl}")
//    private String url;
//
    @Value(("${qiniu.bucket}"))
    private  String bucket;

    @Value("${qiniu.accessKey}")
    private String accessKey;

    @Value("${qiniu.secretKey}")
    private String secretKey;

    @Value("${nginx.group}")
    private String group;


    /**
     * 上传文件
     *
     * @param upfile 文件对象
     * @return 文件访问地址,不带分组的路径  M00/00/00/rBLnQ17TRjmASpWWAAA0UWdASJs550.png
     * @throws IOException s
     */
    public String uploadFile(MultipartFile upfile) throws IOException {

        InputStream inputStream = (InputStream) upfile.getInputStream();
//        String uuid = UUID.randomUUID().toString();
        String fileName = upfile.getOriginalFilename();//获取文件名
        fileName = getFileName(fileName);
        fileName =  group + "/" + fileName;
        String path = QiniuUtil.uploadQNImg(inputStream, fileName); // KeyUtil.genUniqueKey()生成图片的随机名
        System.out.println("七牛云返回的图片链接:" + path);
        return path;
    }
    //在文件名后缀前加一个时间戳
    private String getFileName(String fileName) {
        int index = fileName.lastIndexOf(".");
        final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyymmddHHmmss");  //设置时间格式
        String nowTimeStr = sDateFormate.format(new Date()); // 当前时间
        fileName = fileName.substring(0, index) + "_" + nowTimeStr + fileName.substring(index);
        return fileName;
    }

    /**
     * 文件下载
     * @param groupName 组名           如：group1
     * @param path 不带组名的文件路径  如：M00/00/00/rBLnQ165PGKAICk_AAA0UWdASJs298_60x60.png
     * @param downUrl 下载到哪的目录   如：C:\\Users\\Linging\\Desktop"
     */
    public void downFile(String groupName, String path, String downUrl){
        try {
            File file = new File(path);
            String path1 = file.getPath();
            String suffix = path1.substring(path1.lastIndexOf("."));
            byte[] bytes = storageClient.downloadFile(groupName, path, new DownloadByteArray());
            String url = downUrl+"\\"+ System.currentTimeMillis()+suffix;   //下载的路径
            FileOutputStream stream = new FileOutputStream(url);
            stream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除服务器文件
     * @param key 文件名称
     */
    public void deleteFile(String key){
//        String imagePath = upUrl+"\\"+filename;//图片路径
//        File file = new File(imagePath);
//        if(file.exists()){//文件存在删除文件
//            file.delete();
//        }
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, new Configuration());
        try {
            bucketManager.delete(bucket, key);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }
}